import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_wisave/widgets/AppColors.dart';
import 'package:flutter_wisave/widgets/indicator.dart';
import 'package:flutter_wisave/widgets/lineChartSample.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:flutter_wisave/BasePage/BasePage.dart';

class HotEnergyView extends BasePage {
  const HotEnergyView({super.key});

  @override
  _HotEnergyViewState createState() => _HotEnergyViewState();
}

class _HotEnergyViewState extends BasePageState<HotEnergyView> {
  final dynamic dataRank = {
    'rank': '0',
    'heatValueRatio': '0',
    'heatValue': '0'
  };

  final dynamic lineChartData = {
    'heatValueRatio': [],
    'heatValue': [],
  };
  List<String> xTitle = ['12:00', '12:20', '12:40', '1:00', '1:20', '1:40'];

  @override
  void initState() {
    super.initState();
    _fetchHeatValueHourAvgList();
    _fetchHeatValueHourList();
  }

  Future<void> _fetchHeatValueHourAvgList() async {
    try {
      final response = await networkService.get(
        '/plcTimer/heatvaluehour/heatValueHourAvglist',
        queryParameters: {'companyId': 1},
      );
      print('Heat Value Hour Avg List: ${response.data}');
      setState(() {
        dataRank['rank'] = '${response.data?['data']?['rank'] ?? "0"}';
        dataRank['heatValueRatio'] =
            '${response.data?['data']?['heatValueRatio'] ?? "0"}';
        dataRank['heatValue'] =
            '${response.data?['data']?['heatValue'] ?? "0"}';
      });
    } catch (e) {
      print('Error fetching heat value hour avg list: $e');
    }
  }

  Future<void> _fetchHeatValueHourList() async {
    try {
      final response = await networkService.get(
          '/plcTimer/heatvaluehour/heatValueHourlist',
          queryParameters: {'companyId': 1});
      print('Heat Value Hour List: ${response.data}');
      setState(() {
        if (response.data?['rows'] != null) {
          final total = response.data?['total'] as int;
          for (var i = 0; i < total; i++) {
            final row = response.data?['rows'][i];
            final heatValueRatio = DateTime.parse(row['createTime'] as String);
            final heatValue = row['heatValue'] as double;
            lineChartData['heatValueRatio'].add(heatValueRatio);
            lineChartData['heatValue'].add(heatValue);

            final formattedTime =
                '${heatValueRatio.hour}:${heatValueRatio.minute}';
            lineChartData['xTitle'].add(formattedTime);
          }
        }
      });
    } catch (e) {
      print('Error fetching heat value hour list: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    // 获取屏幕的宽度和高度
    final mediaQuery = MediaQuery.of(context);
    final screenWidth = mediaQuery.size.width;

    final xTitle = lineChartData['xTitle'];

    return Container(
      padding: const EdgeInsets.all(15.0),
      margin: const EdgeInsets.symmetric(vertical: 4.0, horizontal: 8.0),
      decoration: const BoxDecoration(
        color: Colors.transparent,
      ),
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.only(top: 10),
            child: Container(
              padding: EdgeInsets.all(16.0),
              decoration: BoxDecoration(
                color: AppColors.cardColor,
                borderRadius: BorderRadius.circular(8.0),
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.2),
                    blurRadius: 6.0,
                  ),
                ],
              ),
              child: Stack(
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '效率评估',
                        style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: AppColors.textPrimary),
                      ),
                      Center(
                        child: Row(
                          mainAxisSize: MainAxisSize.max,
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Expanded(
                              child: Center(
                                child: Stack(
                                  children: [
                                    Padding(
                                      padding: const EdgeInsets.only(top: 1.0),
                                      child: Image(
                                        image: AssetImage(
                                            'assets/images/centre/toppieBg02.png'),
                                        width: 150,
                                        height: 100,
                                      ),
                                    ),
                                    Positioned(
                                      top: 60,
                                      left: 0,
                                      right: 0,
                                      child: Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        crossAxisAlignment:
                                            CrossAxisAlignment.center,
                                        children: [
                                          Text(
                                              "${double.parse(dataRank['heatValue']).toStringAsFixed(0)}%",
                                              style: TextStyle(
                                                fontSize: 25,
                                                fontWeight: FontWeight.bold,
                                                color: Color(0xFFFCAA3F),
                                              )),
                                          // Text('总数',
                                          //     style: TextStyle(
                                          //       fontSize: 12,
                                          //       color: Color(0xFF4E5969),
                                          //     )),
                                        ],
                                      ),
                                    )
                                  ],
                                ),
                              ),
                            ),
                            Expanded(
                              child: Center(
                                child: Column(
                                  children: [
                                    SizedBox(
                                      height: 15,
                                    ),
                                    Indicator(
                                      color: Color(0xFF2AB6F7),
                                      text: '优：Q≥60%',
                                      isSquare: true,
                                      size: 12,
                                    ),
                                    SizedBox(
                                      height: 5,
                                    ),
                                    Indicator(
                                      color: Color(0xFFFCAA3F),
                                      text: '良：40%≤Q≤60%',
                                      isSquare: true,
                                    ),
                                    SizedBox(
                                      height: 5,
                                    ),
                                    Indicator(
                                      color: Color(0xFFFD5864),
                                      text: '差：Q＜40%',
                                      isSquare: true,
                                    ),
                                  ],
                                ),
                              ),
                            )
                          ],
                        ),
                      )
                    ],
                  ),
                ],
              ),
            ),
          ),
          SizedBox(height: 10),
          Padding(
            padding: const EdgeInsets.only(top: 10),
            child: Container(
              padding: EdgeInsets.all(16.0),
              decoration: BoxDecoration(
                color: AppColors.cardColor,
                borderRadius: BorderRadius.circular(8.0),
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.2),
                    blurRadius: 6.0,
                  ),
                ],
              ),
              child: Stack(
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '热平衡分析',
                        style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: AppColors.textPrimary),
                      ),
                      Center(
                        child: Row(
                          mainAxisSize: MainAxisSize.max,
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Expanded(
                              child: Center(
                                child: Stack(
                                  children: [
                                    Padding(
                                      padding: const EdgeInsets.only(top: 20.0),
                                      child: Image(
                                        image: AssetImage(
                                            'assets/images/centre/toppieBg.png'),
                                        width: 200,
                                        height: 200,
                                      ),
                                    ),
                                    Positioned(
                                      top: 85,
                                      left: 0,
                                      right: 0,
                                      child: Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        crossAxisAlignment:
                                            CrossAxisAlignment.center,
                                        children: [
                                          Text(
                                              double.parse(
                                                      dataRank['heatValue'])
                                                  .toStringAsFixed(0),
                                              style: TextStyle(
                                                fontSize: 25,
                                                fontWeight: FontWeight.bold,
                                                color: Color(0xFF2AB6F7),
                                              )),
                                          Text('钢坯吸热',
                                              style: TextStyle(
                                                fontSize: 13,
                                                color: AppColors.textSecondary,
                                              )),
                                        ],
                                      ),
                                    )
                                  ],
                                ),
                              ),
                            ),
                            Expanded(
                              child: Center(
                                child: Column(
                                  children: [
                                    SizedBox(
                                      height: 15,
                                    ),
                                    Indicator(
                                      color: Color(0xFF2AB6F7),
                                      text: '钢坯吸热：60%',
                                      isSquare: true,
                                      size: 12,
                                    ),
                                    SizedBox(
                                      height: 5,
                                    ),
                                    Indicator(
                                      color: Color(0xFF53E0B1),
                                      text: '钢坯吸热：60%',
                                      isSquare: true,
                                    ),
                                    SizedBox(
                                      height: 5,
                                    ),
                                    Indicator(
                                      color: Color(0xFFFCAA3F),
                                      text: '散热损失：15%',
                                      isSquare: true,
                                    ),
                                    SizedBox(
                                      height: 5,
                                    ),
                                    Indicator(
                                      color: Color(0xFFFD5864),
                                      text: '水梁损失：5%',
                                      isSquare: true,
                                    ),
                                  ],
                                ),
                              ),
                            )
                          ],
                        ),
                      )
                    ],
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 10),
          Padding(
            padding: const EdgeInsets.only(top: 10),
            child: Container(
              padding: EdgeInsets.all(16.0),
              decoration: BoxDecoration(
                color: AppColors.cardColor,
                borderRadius: BorderRadius.circular(8.0),
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.2),
                    blurRadius: 6.0,
                  ),
                ],
              ),
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '热效率排位',
                      style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                          color: AppColors.textPrimary),
                    ),
                    const SizedBox(height: 16.0),
                    const LineChartSample2(
                      spots: [20, 40, 90, 30, 80, 20],
                      xTitle: [
                        '12:00',
                        '12:20',
                        '12:40',
                        '1:00',
                        '1:20',
                        '1:40'
                      ], // 传递 xTitle 数据
                    ),
                  ]),
            ),
          ),
          const SizedBox(height: 10),
          Padding(
            padding: const EdgeInsets.only(top: 10),
            child: Container(
              padding: EdgeInsets.all(16.0),
              decoration: BoxDecoration(
                color: AppColors.cardColor,
                borderRadius: BorderRadius.circular(8.0),
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.2),
                    blurRadius: 6.0,
                  ),
                ],
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '热效率对比',
                    style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        color: AppColors.textPrimary),
                  ),
                  const SizedBox(height: 16.0),
                  Row(
                      mainAxisSize: MainAxisSize.max,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        ..._meanWithType(
                            0,
                            '${dataRank?['heatValueRatio'] ?? 0}%',
                            screenWidth),
                        // ..._meanWithType(
                        //     1, '${dataRank?['rank'] ?? 0}', screenWidth),
                      ]),
                  const SizedBox(height: 26.0),
                  Text(
                    '每周热效率平均值同上周热效率进行对比',
                    style:
                        TextStyle(fontSize: 12, color: AppColors.textSecondary),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

List<Widget> _meanWithType(num type, String content, double screenWidth) {
  return [
    Container(
      margin: EdgeInsets.only(left: type == 1 ? 9.0 : 0), // 设置间距
      height: 94, // 调整背景图的高度
      width: screenWidth - 80, //- 50,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(AppColors.isDarkMode
              ? 'assets/images/centre/hot_heat_bg_b.png'
              : 'assets/images/centre/hot_heat_bg.png'), //'assets/images/centre/hot_bg${type + 1}.png'
          fit: BoxFit.cover,
        ),
        borderRadius: BorderRadius.circular(8.0),
      ),
      child: Stack(
        children: [
          Positioned(
            bottom: 10,
            width: screenWidth - 80, //screenWidth / 2 - 50,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  type == 0 ? '热效率性能变化' : '热效率年度排位',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: AppColors.textPrimary,
                    fontSize: 14,
                  ),
                ),
                Text(
                  content,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      color: type == 0 ? Color(0xFFFD5864) : Color(0xFF2AB6F7),
                      fontSize: 30,
                      fontWeight: FontWeight.bold),
                ),
              ],
            ),
          ),
        ],
      ),
    ),
  ];
}

class PieChartSample2 extends StatefulWidget {
  const PieChartSample2({super.key});

  @override
  State<StatefulWidget> createState() => PieChart2State();
}

class PieChart2State extends State {
  int touchedIndex = -1;

  @override
  Widget build(BuildContext context) {
    return AspectRatio(
      aspectRatio: 1.6,
      child: Stack(
        children: <Widget>[
          Positioned(
            left: 40, // 添加此行以将 AspectRatio 左移
            top: 50,
            width: 100,
            height: 100,
            child: AspectRatio(
              aspectRatio: 1,
              child: PieChart(
                PieChartData(
                  pieTouchData: PieTouchData(
                    touchCallback: (FlTouchEvent event, pieTouchResponse) {
                      setState(() {
                        if (!event.isInterestedForInteractions ||
                            pieTouchResponse == null ||
                            pieTouchResponse.touchedSection == null) {
                          touchedIndex = -1;
                          return;
                        }
                        touchedIndex = pieTouchResponse
                            .touchedSection!.touchedSectionIndex;
                      });
                    },
                  ),
                  borderData: FlBorderData(
                    show: false,
                  ),
                  sectionsSpace: 3,
                  centerSpaceRadius: 70,
                  sections: showingSections(),
                ),
              ),
            ),
          ),
          const Positioned(
            top: 70,
            right: 20,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.end,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Indicator(
                  color: Color(0xFF2AB6F7),
                  text: '优：Q >= 60%',
                  isSquare: true,
                  size: 12,
                ),
                SizedBox(
                  height: 15,
                ),
                Indicator(
                  color: Color(0xFFFCAA3F),
                  text: '良：Q >= 50%',
                  isSquare: true,
                ),
                SizedBox(
                  height: 15,
                ),
                Indicator(
                  color: Color(0xFFFD5864),
                  text: '差：Q < 50%',
                  isSquare: true,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  List<PieChartSectionData> showingSections() {
    return List.generate(3, (i) {
      final isTouched = i == touchedIndex;
      final fontSize = isTouched ? 25.0 : 20.0;
      final radius = isTouched ? 10.0 : 10.0;
      const shadows = [Shadow(color: Colors.black, blurRadius: 11)];
      switch (i) {
        case 0:
          return PieChartSectionData(
            color: Color(0xFF2AB6F7),
            value: 40,
            showTitle: false,
            radius: radius,
          );
        case 1:
          return PieChartSectionData(
            color: Color(0xFFFCAA3F),
            value: 30,
            showTitle: false,
            radius: radius,
          );
        case 2:
          return PieChartSectionData(
            color: Color(0xFFFD5864),
            value: 15,
            showTitle: false,
            radius: radius,
          );
        default:
          throw Error();
      }
    });
  }
}
